package com.poptap.base.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Order;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.poptap.base.domain.Category;
import com.poptap.base.util.CollectionUtil;
import com.poptap.base.util.StringUtil;

@Service
public class CategoryServiceImpl implements CategoryService {

	@Autowired
	private MongoTemplate template;

	@Override
	public boolean createCatalog(String name) {
		if(StringUtil.isNotEmptyOrWhitespaceOnly(name)) {
			Category catalog = new Category();
			catalog.setName(name);
			catalog.setLevel(1);
			catalog.setDeleted(false);
			catalog.setCreateTime(new Date());
			template.save(catalog);
			return true;
		} else {
			return false;
		}
	}

	@Override
	public boolean createCategory(String parentId, String name) {
		if(StringUtil.isEmptyOrWhitespaceOnly(name)) {
			if(StringUtil.isNotEmptyOrWhitespaceOnly(parentId)) {
				Category catalog = find(parentId);
				
				Category category = new Category();
				category.setParent(catalog);
				category.setDeleted(false);
				category.setCreateTime(new Date());
				category.setName(name);
				category.setLevel(catalog.getLevel() + 1);
				template.save(category);
				
				catalog.getChildren().add(category);
				template.save(catalog);
				return true;
			} else {
				return createCatalog(name);
			}
		} else {
			return false;
		}
	}
	
	@Override
	public Category find(String id) {
		return template.findById(new ObjectId(id), Category.class);
	}

	@Override
	public boolean updateCategory(String id, String name) {
		if(StringUtil.isEmptyOrWhitespaceOnly(name)) {
			return false;
		}
		Category category = find(id);
		category.setName(name);
		template.save(category);
		return true;
	}

	@Override
	public List<Category> findAllCatalogs() {
		Query query = new Query(Criteria.where("level").is(1));
		query.sort().on("createTime", Order.ASCENDING);
		List<Category> categories = template.find(query, Category.class);
		if(CollectionUtil.isEmpty(categories)) {
			return new ArrayList<Category>();
		} else {
			return categories;
		}
	}

	@Override
	public List<Category> findCategories(String id) {
		Category parent = find(id);
		if(parent == null || CollectionUtil.isEmpty(parent.getChildren())) {
			return new ArrayList<Category>();
		} else {
			return parent.getChildren();
		}
	}
	
	
}
